<template>
  <div>
    <div>
      <a-button type="primary" @click="updateNovel">更新章节</a-button>
      <a-button type="primary" @click="handleCache(false)">缓存所有</a-button>
      <a-button type="primary" @click="handleCache(true)">强制更新缓存</a-button>
      <a-button type="primary" @click="genEpub" :loading="epubLoading">生成Epub</a-button>
      <a-button type="primary" @click="genMobi" :loading="mobiLoading">生成mobi</a-button>
    </div>
    <div class="novel-head">
        <div class="novel-head-main">
            <div class="sidebar">
                <div id="fmimg">
                  <img :src="detail.coverUrl" width="120" height="150" >
                </div>
            </div>
            <div class="main">
                <div class="info">
                    <h1>{{ detail.name }}</h1>
                    <p>
                        作&nbsp;&nbsp;者：{{ detail.author }}</p>
                    <p>
                    <p>
                        分&nbsp;&nbsp;类：{{ detail.kind }}</p>
                    <p>
                    <p>最后更新:{{ detail.updatedAt }}</p>
                    <a v-if="detail.mobi" :href="detail.mobi">mobi下载 <span>更新时间: {{ detail.mobiUpdate }}</span></a>
                </div>
            </div>
            </div>
            <div class="intro" v-html="detail.intro">
            </div>
        </div>
        <div class="box_con">
                <h2 style="text-align: center;">《{{ detail.name }}》正文</h2>
            <a-row class="list">
                <a-col :span="12" v-for="chapter in detail.chapters" :key="chapter.chapterUrl">
                  <a @click="$router.push(`/novel/chapter?novelId=${id}&chapterId=${chapter.chapterUrl}`)">
                  {{ chapter.chapterName }}
                  <span class="chapter-status" v-if="chapterListLoading || chapter.cached">{{  getStatus(chapter) }}</span>
                  </a>
                </a-col>
            </a-row>
        </div>
  </div>
</template>

<script>
import { KINDLEGEN } from '@/api/constant'
import { getNovel, updateNovel } from '@/api'
import {
  CALLBACK,
  CACHE_CHAPTER_LIST,
  GEN_MOBI,
  GEN_EPUB
} from '@/api/channel'
import { mapMutations, mapState } from 'vuex'
import { status } from '@/api/constant'

export default {
  props: {
    id: {
      type: String
    }
  },
  data () {
    return {
      detail: {},
      mobiLoading: false,
      epubLoading: false
    }
  },
  computed: {
    ...mapState(['chapterList', 'chapterListLoading'])
    // detailJSON () {
    //   return JSON.stringify(this.detail, null, '\t')
    // }
  },
  created () {
    this.getDetail()
    // this.$electron.ipcRenderer.on(CACHE_CHAPTER_LIST + CALLBACK, (event, arg) => {
    //   if (arg.code === 200) {
    //     if (arg.data.status === 'done') {
    //       this.loading = false
    //       this.$message.success('全部缓存完毕')
    //       this.getDetail()
    //     } else {
    //       this.loadingList[arg.data.item.chapterUrl] = status[0]
    //     }
    //   } else {
    //     this.$message.error(arg.message)
    //     this.loading = false
    //   }
    // })

    // this.$electron.ipcRenderer.on(GEN_MOBI + CALLBACK, (event, arg) => {
    //   if (arg.code === 200) {
    //     if (arg.data) {
    //       this.mobiLoading = false
    //       this.$confirm({
    //         title: '制作成功！',
    //         content: '是否打开所在文件夹',
    //         onOk: () => {
    //           this.$electron.shell.showItemInFolder(arg.data)
    //           return Promise.resolve()
    //         }
    //       })
    //     }
    //   } else {
    //     this.$message.error(arg.message)
    //     this.mobiLoading = false
    //   }
    // })

    // this.$electron.ipcRenderer.on(GEN_EPUB + CALLBACK, (event, arg) => {
    //   if (arg.code === 200) {
    //     if (arg.data) {
    //       this.epubLoading = false
    //       this.$confirm({
    //         title: '制作成功！',
    //         content: '是否打开所在文件夹',
    //         onOk: () => {
    //           this.$electron.shell.showItemInFolder(arg.data)
    //           return Promise.resolve()
    //         }
    //       })
    //     }
    //   } else {
    //     this.$message.error(arg.message)
    //     this.epubLoading = false
    //   }
    // })
  },
  methods: {
    ...mapMutations(['SAVE_CHAPTER_LIST']),
    genMobi () {
      if (this.detail.chapters.every(x => x.cached)) {
        this.$confirm({
          title: '提示',
          content: '是否制作mobi?',
          onOk: () => {
            this.$socket.sendObj({ type: GEN_MOBI, payload: { novelId: this.id } })
            this.mobiLoading = true
            return Promise.resolve()
          }
        })
      } else {
        this.$message.error("请确认所有章节已缓存")
      }
    },
    genEpub () {
      this.$confirm({
        title: '提示',
        content: '是否制作Epub?',
        onOk: () => {
          this.$socket.sendObj({ type: GEN_MOBI, payload: { novelId: this.id } })
          this.epubLoading = true
          return Promise.resolve()
        }
      })
    },
    updateNovel () {
      return updateNovel({ id: this.id, chapters: true }).then(() => {
        return this.getDetail()
      }).then(() => {
        this.$message.success('更新成功！')
      }).catch(e => {
        this.$message.error(e.message)
      })
    },
    getStatus (chapter) {
      if (this.chapterListLoading) {
        return this.chapterList[chapter.chapterUrl] === status[0] ? '(已缓存)' : '(下载中)'
      } else {
        return chapter.cached ? '(已缓存)' : ''
      }
    },
    handleCache (force = false) {
      const loading = {}
      this.detail.chapters.forEach(x => {
        if (force) {
          loading[x.chapterUrl] = status[1]
        } else {
          if (x.cached) {
            loading[x.chapterUrl] = status[0]
          } else {
            loading[x.chapterUrl] = status[1]
          }
        }
      })
      this.SAVE_CHAPTER_LIST(loading)
       this.$socket.sendObj({ type: CACHE_CHAPTER_LIST, payload:  { novelId: this.id, force } })
    },
    getDetail () {
      return getNovel({ id: this.id }).then(res => {
        this.detail = res
      }).catch(e => {
        this.$message.error(e.message)
      })
    }
  }
}
</script>

<style>
.chapter-status {
  color: #666666;
}
.novel-head {
  padding: 16px;
}

.novel-head-main {
  display: flex;
  margin-bottom: 16px;
}

.novel-head-main .sidebar {
  margin-right: 16px;
}
</style>